package com.tianfeng.news.ui.activity.news.search;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.tianfeng.news.R;
import com.tianfeng.news.globle.ConstantUrl;
import com.tianfeng.news.model.bean.news.SearchBean;
import com.tianfeng.news.net.HttpView;
import com.tianfeng.news.net.OkHttpHelper;
import com.tianfeng.news.ui.activity.base.BaseActivity;
import com.tianfeng.news.ui.activity.news.NewsDetailActivity2;
import com.tianfeng.news.ui.adapter.recyclerview.SearchNewsAdapter;
import com.tianfeng.news.ui.adapter.recyclerview.SearchVideoAdapter;
import com.tianfeng.news.ui.adapter.recyclerview.muiltyAdapter.bean.video.VideoListBean;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Dinosa on 2018/1/29.
 */

public class SearchDetailActivity extends BaseActivity implements HttpView
        , BaseQuickAdapter.RequestLoadMoreListener {

    @BindView(R.id.iv_back)
    ImageView mIvBack;
    @BindView(R.id.ev_search)
    EditText mEvSearch;

    @BindView(R.id.rv_search_list)
    RecyclerView rcSearch;

    SearchNewsAdapter newsdapter;
    SearchVideoAdapter videoAdapter;

    String searchKey;

    int page = 1;
    boolean isLeft = true;

    public static String KEY_WORD = "keyWord";


    @Override
    public int getContentLayout() {
        return R.layout.activity_search_detail;
    }

    @Override
    protected void initView(View rootView, Bundle savedInstanceState) {
//        initWebViewSetting();
        //取消文本框弹出；
        getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        initViewPager();

    }

    private void initViewPager() {
        RadioGroup rg_left = findViewById(R.id.content_radiogroup);
        rg_left.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int checkdId) {
                RadioButton rgleft = radioGroup.findViewById(R.id.rg_left);
                RadioButton rgRight = radioGroup.findViewById(R.id.rg_right);
                switch (checkdId) {
                    case R.id.rg_left:
                        initNewsAdapter();
                        rgleft.setTextColor(ContextCompat.getColor(SearchDetailActivity.this, R.color.white_color));
                        rgRight.setTextColor(ContextCompat.getColor(SearchDetailActivity.this, R.color.colorFD7033));
                        page = 1;
                        isLeft=true;
                        doSearch();
                        break;
                    case R.id.rg_right:
                        initVideoAdapter();
                        rgRight.setTextColor(ContextCompat.getColor(SearchDetailActivity.this, R.color.white_color));
                        rgleft.setTextColor(ContextCompat.getColor(SearchDetailActivity.this, R.color.colorFD7033));
                        page = 1;
                        isLeft=false;
                        doSearch();
                        break;
                }
            }
        });

        rcSearch = (RecyclerView) this.findViewById(R.id.rv_search_list);
        rcSearch.setLayoutManager(new LinearLayoutManager(this));
        initNewsAdapter();
    }
    private void initVideoAdapter() {
        videoAdapter = new SearchVideoAdapter(null,null);
        videoAdapter.setOnLoadMoreListener(this);
        rcSearch.setAdapter(videoAdapter);
    }

    private void initNewsAdapter() {
        newsdapter = new SearchNewsAdapter(this,null);
        newsdapter.setOnLoadMoreListener(this);
        newsdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                List<SearchBean.DataBean.NewsBean> data = newsdapter.getData();
                SearchBean.DataBean.NewsBean newsBean = data.get(position);
                startActivity(NewsDetailActivity2.getIntent(SearchDetailActivity.this
                        ,newsBean.getUrl()
                        ,newsBean.getUrlmd5() , "xiaohua" , 1));
            }
        });
        rcSearch.setAdapter(newsdapter);
    }

    @Override
    protected void initData() {
        super.initData();

        searchKey = getIntent().getStringExtra(KEY_WORD);

        if (searchKey != null) {
            mEvSearch.setText(searchKey);
            mEvSearch.setSelection(searchKey.length());
        }
        doSearch();

    }

    private void doSearch() {
        HashMap<String, String> params = new HashMap<>();
        params.put("page", String.valueOf(page));
        params.put("keyword", searchKey.trim());
        params.put("pagesize", "20");
        OkHttpHelper.getAsyncHttp(this, 10001, params, ConstantUrl.REQUEST_SEARCH, this);

        getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
    }


    public static Intent getSearchIntent(Context context, String keyWord) {
        Intent intent = new Intent(context, SearchDetailActivity.class);
        intent.putExtra(KEY_WORD, keyWord);
        return intent;
    }

    /**
     * 这里是搜索的页面；
     */
    @OnClick(R.id.tv_search)
    public void onClickSearch() {
        searchKey = mEvSearch.getText().toString().trim();
        if (!TextUtils.isEmpty(searchKey)) {
            doSearch();
        }
    }

    @OnClick(R.id.iv_back)
    public void onClickBack() {
        finish();
    }

    @Override
    public void onSuccessResult(int requestCode, int returnCode, String returnMsg, String returnData, Map<String, String> paramsMaps) {
        switch (requestCode) {
            case 10001:
                try {
                    Gson gson = new Gson();
                    SearchBean searchBean = gson.fromJson(returnData, SearchBean.class);
                    SearchBean.DataBean data = searchBean.getData();
                    if (data != null){
                        if (isLeft){
                            List<SearchBean.DataBean.NewsBean> news = data.getNews();
                            if (page == 1) {
                                if (news == null || news.size() == 0) {
                                    newsdapter.loadMoreEnd();
                                } else {
                                    newsdapter.setNewData(news);
                                    newsdapter.loadMoreComplete();
                                }
                            } else {
                                if (news == null || news.size() == 0) {
                                    newsdapter.loadMoreEnd();
                                } else {
                                    newsdapter.addData(news);
                                    newsdapter.loadMoreComplete();
                                }
                            }

                        }else {
                            List<SearchBean.DataBean.VideoBean> video = data.getVideo();
                            List<MultiItemEntity> multiItemEntities = filterData(video);
                            if (page == 1) {
                                if (video == null || video.size() == 0) {
                                    videoAdapter.loadMoreEnd();
                                } else {
                                    videoAdapter.setNewData(multiItemEntities);
                                    videoAdapter.loadMoreComplete();
                                }
                            } else {
                                if (video == null || video.size() == 0) {
                                    videoAdapter.loadMoreEnd();
                                } else {
                                    videoAdapter.addData(multiItemEntities);
                                    videoAdapter.loadMoreComplete();
                                }
                            }
                            videoAdapter.notifyDataSetChanged();
                        }
                    }

                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }

                break;
        }
    }

    private List<MultiItemEntity> filterData(List<SearchBean.DataBean.VideoBean> list) {

        ArrayList<MultiItemEntity> multiItemEntities = new ArrayList<>();

        if (list != null && list.size() > 0) {

            for (SearchBean.DataBean.VideoBean videoBean : list) {

                    multiItemEntities.add(getVideo(videoBean));
                    continue;
                }

        }

        return multiItemEntities;
    }

    private MultiItemEntity getVideo(SearchBean.DataBean.VideoBean videoBean) {

        //这里表示是视频的逻辑
        MultiItemEntity multiItemEntity = null;

        String title = videoBean.getTitle();
        String source = videoBean.getSource();
        String urlMd5 = videoBean.getUrlmd5();
        String imageUrl = "";
        String item_id = videoBean.getItem_id();
        String group_id = videoBean.getGroup_id();
        String video_id = videoBean.getVideo_id();
        String publishTime = videoBean.getPublish_time();
        long duration = Long.valueOf(videoBean.getVideo_duration()).longValue();

        try {
            if(videoBean.getLarge_image_list() != null) {
                imageUrl = videoBean.getLarge_image_list().get(0).getUrl();
//                imageUrl = videoBean.getLarge_image_list();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        multiItemEntity = new VideoListBean(source, urlMd5, title, imageUrl, item_id, group_id, video_id, publishTime, duration);

        return multiItemEntity;
    }

    @Override
    public void onFailure(int callbackId, String data) {

    }


    @Override
    public void onLoadMoreRequested() {
        page++;
        doSearch();
    }

}
